package org.example.forum.services.impl;

import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.dao.UserMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.services.IUserService;
import org.example.forum.utils.MD5Utils;
import org.example.forum.utils.StringUtil;
import org.example.forum.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //1、非空校验
        if ((user == null)
                || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //统一抛出ApplicationException异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2、按用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if (existsUser != null) {
            log.info(ResultCode.AILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }
        //3、新增用户流程，设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //当前日期
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        //写入数据库
        int row = userMapper.insertSelective(user);
        if (row < 1) {
            log.info(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功，username="+user.getUsername()+".");
    }

    @Override
    public User selectByUserName(String username) {
        //非空校验
        if (StringUtil.isEmpty(username)) {
            System.out.println("进入为空判定");
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询的结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //1、非空校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //2、按用户名查询用户信息
        User user = selectByUserName(username);
        //3、对查询结果做非空校验
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString()+" username = "+username+".");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //4、做密码的校验(要根据明文和盐生成密文，和数据库中的密码对比，如果相同即代表校验通过
        String encryptPassword = MD5Utils.md5Salt(password, user.getSalt());
        //5、用数据库中存的用户密码进行比较
        if (!encryptPassword.equalsIgnoreCase(user.getPassword()))  {//打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString()+",密码输入错误,username="+username+".");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //6、登录成功返回用户信息
        log.info("登录成功,username="+username+".");
        return user;
    }

    @Override
    public User selectById(Long id) {
        //1、非空校验
        if (id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //2、调用DAO查询数据库，并获取对象
        User user = userMapper.selectByPrimaryKey(id);
        //3、返回结果
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        //更新帖子数量
        //重新创建一个原来更新的对象，设置要更新的属性，调用动态SQL更新方法，就不会全部都更新了
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.ERROR_SERVICES.toString()+"，受影响的行数不等一");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
    //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.ERROR_IS_NULL.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        //更新帖子数量
        //重新创建一个原来更新的对象，设置要更新的属性，调用动态SQL更新方法，就不会全部都更新了
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        //判断 -1 之后，用户发帖数是否小于0
        if (updateUser.getArticleCount() < 0) {
            //如果小于0则设置为0
            updateUser.setArticleCount(0);
        }
        //更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString()+"，受影响的行数不等一");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //1、非空校验
        if (user == null || user.getId() == null || user.getId() <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2、校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3、校验传入的参数（如果全部为空也不行
        //方法一：用if（&&）把每一个都校验一遍
        //方法二：定义一个标志位 边赋值边校验（当每一个都不为空的时候设置为true
        boolean checkAttr = false; //false表示校验没有通过

        //3.1、定义一个专门用来更新的对象，防止用户传入的user设置了多余的属性，覆盖原数据库中没有经过校验的字段
        User updateUser = new User();
        //3.2、设置用户id
        updateUser.setId(user.getId());
        //3.3、对每一个参数进行校验，并处理赋值
        //校验用户名
        if (!StringUtil.isEmpty(user.getUsername())
                && !user.getUsername().equals(existsUser.getUsername())) {
            //需要更新用户名（登录名）时，进行唯一性的校验。（因为登录名全系统是唯一的）
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null) {
                //说明用户已存在，需要抛异常
                log.warn(ResultCode.AILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
            }
            //没有找到相应的用户，表示这个用户名是唯一的，可以修改
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr = true;
        }
        //校验昵称
        if (!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsUser.getNickname())) {
            updateUser.setNickname(user.getNickname());
            //更新标志位
            checkAttr = true;
        }
        //校验性别
        if (user.getGender() != null
                && user.getGender() != existsUser.getGender()) {
            updateUser.setGender(user.getGender());
            //合法性校验
            if (updateUser.getGender() > 2 || updateUser.getGender() < 0) {
                updateUser.setGender((byte) 2);
            }
            //更新标志位
            checkAttr = true;
        }
        //校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsUser.getEmail())) {
            updateUser.setEmail(user.getEmail());
            //更新标志位
            checkAttr = true;
        }
        //校验电话号码
        if (!StringUtil.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(existsUser.getPhoneNum())) {
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            checkAttr = true;
        }
        //校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existsUser.getRemark())) {
            updateUser.setRemark(user.getRemark());
            //更新标志位
            checkAttr = true;
        }
        //只要有某一个修改了，checkAttr标志位都会被设置为true。
        //如果标志位还是为false，那么证明不需要执行更新
        if (!checkAttr) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //4、调用DAO，执行SQL
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED.toString()+",受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //非空校验
        if (id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //通过id查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            //用户不存在
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验旧密码是否和数据库密码一致
        //对旧密码进行加密获取密文
        String oldEncryptPassword = MD5Utils.md5Salt(oldPassword, user.getSalt());
        if (!oldEncryptPassword.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_USER_PASSWORD.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_PASSWORD));
        }
        //生成一个新的盐值
        String salt = UUIDUtil.getUUID_32();
        //生成新密码的密文
        String newEncryptPassword = MD5Utils.md5Salt(newPassword,salt);
        //构造更新的对象
        User updateUser = new User();
        Date date  = new Date();
        updateUser.setId(user.getId()); //用户id
        updateUser.setPassword(newEncryptPassword); //新密码对应的密文
        updateUser.setSalt(salt);   //新密码对应的盐
        updateUser.setUpdateTime(date); //更新时间
        //调用DAO更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+",受影响的行数不等于1");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }


}
